//
//  CutPriceViewController.m
//  LoveCar
//
//  Created by dlios on 15/5/25.
//  Copyright (c) 2015年 薛森鸿. All rights reserved.
//

#import "CutPriceViewController.h"
#import <AFNetworking/AFNetworking.h>
#import <SDWebImage/UIImageView+WebCache.h>
#import "MJRefresh.h"
#import "CutPriceModel.h"
#import "CutPriceCell.h"
#import "CutPriceDetailController.h"

@interface CutPriceViewController ()<UITableViewDataSource, UITableViewDelegate>

@property (nonatomic, retain) UITableView *table;
@property (nonatomic, retain) NSMutableArray *array;

@end

@implementation CutPriceViewController
- (void)dealloc
{
    [_table release];
    [_array release];
    [super dealloc];
}
- (void)viewDidLoad {
    [super viewDidLoad];
    self.array = [NSMutableArray array];
    [self step];
    [self createTable];
    [self setupRefresh];
}

- (void)step
{
    self.navigationItem.hidesBackButton = YES;
    
    self.navigationController.navigationBar.translucent = NO;
    self.tabBarController.tabBar.translucent = NO;
    self.view.backgroundColor = [UIColor redColor];
    UIView *title = [[UIView alloc] initWithFrame:CGRectMake(0, 0, 150, 30)];
    [self.navigationItem setTitleView:title];
    [title release];
    
    UIButton *a = [[UIButton alloc] initWithFrame:CGRectMake(0, 0, 70, 30)];
    [a setTitle:@"活动" forState:UIControlStateNormal];
    [a setTitleColor:[UIColor lightGrayColor] forState:UIControlStateNormal];
    a.titleLabel.font = [UIFont systemFontOfSize:14];
    [a addTarget:self action:@selector(activityAction:) forControlEvents:UIControlEventTouchUpInside];
    [title addSubview:a];
    
    UIButton *b = [[UIButton alloc] initWithFrame:CGRectMake(80, 0, 70, 30)];
    [b setTitle:@"降价" forState:UIControlStateNormal];
    [b setTitleColor:[UIColor blueColor] forState:UIControlStateNormal];
    [title addSubview:b];
    [a release];
    [b release];
    
}
- (void)activityAction:(id)sender
{
    [self.navigationController popToRootViewControllerAnimated:YES];
}
// 创建table
- (void)createTable
{
    self.table = [[UITableView alloc] initWithFrame:CGRectMake(0, 0, self.view.frame.size.width, self.view.frame.size.height - 64 - 49) style:UITableViewStylePlain];
    _table.delegate = self;
    _table.dataSource = self;
    [self.table registerClass:[CutPriceCell class] forCellReuseIdentifier:@"cell11"];
    [self.view addSubview:_table];
    [_table setScrollsToTop:YES];
    //_table.separatorStyle = UITableViewCellSeparatorStyleNone;
    [_table release];
}
// 更新cell
- (void)reloadDataForCell
{
    NSString *str = @"http://mrobot.pcauto.com.cn/v3/price/promotionList?areaId=248&pageNo=1&pageSize=20&orderBy=popularity";
    
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    __block CutPriceViewController *cutPriceViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        [cutPriceViewController.array removeAllObjects];
        for (NSDictionary *sdic in [dic objectForKey:@"data"]) {
            CutPriceModel *model = [[CutPriceModel alloc] init];
            [model setValuesForKeysWithDictionary:sdic];
            [cutPriceViewController.array addObject:model];
        }
        
        [cutPriceViewController.table reloadData];
        [cutPriceViewController.table headerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}
/**
 *  集成刷新控件
 */
- (void)setupRefresh
{
    // 1.下拉刷新(进入刷新状态就会调用self的headerRereshing)
    [self.table addHeaderWithTarget:self action:@selector(headerRereshing)];
    //#warning 自动刷新(一进入程序就下拉刷新)
    [self.table headerBeginRefreshing];
    
    // 2.上拉加载更多(进入刷新状态就会调用self的footerRereshing)
    [self.table addFooterWithTarget:self action:@selector(footerRereshing)];
}

#pragma mark 开始进入刷新状态
- (void)headerRereshing
{
    [self reloadDataForCell];
}

- (void)footerRereshing
{
    NSString *str = [NSString stringWithFormat:@"http://mrobot.pcauto.com.cn/v3/price/promotionList?areaId=248&pageNo=%ld&pageSize=20&orderBy=popularity", self.pageCount];
    AFHTTPRequestOperationManager *m = [AFHTTPRequestOperationManager manager];
    m.responseSerializer = [AFHTTPResponseSerializer serializer];
    __block CutPriceViewController *cutPriceViewController = self;
    [m GET:str parameters:nil success:^(AFHTTPRequestOperation *operation, id responseObject) {
        NSData *data = operation.responseData;
        NSDictionary *dic = [NSJSONSerialization JSONObjectWithData:data options:   NSJSONReadingMutableContainers error:nil];
        for (NSDictionary *sdic in [dic objectForKey:@"data"]) {
            CutPriceModel *model = [[CutPriceModel alloc] init];
            [model setValuesForKeysWithDictionary:sdic];
            [cutPriceViewController.array addObject:model];
        }
        cutPriceViewController.pageCount += 1;
        [cutPriceViewController.table reloadData];
        [cutPriceViewController.table footerEndRefreshing];
    } failure:^(AFHTTPRequestOperation *operation, NSError *error) {
        
    }];
}


- (CGFloat)tableView:(UITableView *)tableView heightForRowAtIndexPath:(NSIndexPath *)indexPath
{
    return 130;
}
- (NSInteger)tableView:(UITableView *)tableView numberOfRowsInSection:(NSInteger)section
{
    
    return self.array.count;
}
- (UITableViewCell *)tableView:(UITableView *)tableView cellForRowAtIndexPath:(NSIndexPath *)indexPath
{
    
    CutPriceCell *cell = [tableView dequeueReusableCellWithIdentifier:@"cell11"];
    CutPriceModel *model = [self.array objectAtIndex:indexPath.row];
    cell.name.text = model.modelName;
    cell.dealer.text = model.dealerName;
    cell.price.text = [NSString stringWithFormat:@"%@万", model.price];
    cell.mprice.text = [NSString stringWithFormat:@"%@万", model.modelPrice];
    [cell.tel setTitle:model.phone forState:UIControlStateNormal];
    cell.phoneNum = model.phone;
    NSInteger cut = [model.modelPrice integerValue] - [model.price integerValue];
    cell.cutprice.text = [NSString stringWithFormat:@"%.2f万", (float)cut];
    
    return cell;
    return nil;
}

- (void)tableView:(UITableView *)tableView didSelectRowAtIndexPath:(NSIndexPath *)indexPath
{
    [tableView deselectRowAtIndexPath:indexPath animated:YES];
    CutPriceModel *model = [self.array objectAtIndex:indexPath.row];
    CutPriceDetailController *detail = [[CutPriceDetailController alloc] init];
    detail.dealerNewsId = model.dealerNewsId;
    [self.navigationController pushViewController:detail animated:YES];
    [detail release];
}
// 分割线前移
-(void)viewDidLayoutSubviews
{
    if ([_table respondsToSelector:@selector(setSeparatorInset:)]) {
        [_table setSeparatorInset:UIEdgeInsetsMake(0,0,0,0)];
    }
    
    if ([_table respondsToSelector:@selector(setLayoutMargins:)]) {
        [_table setLayoutMargins:UIEdgeInsetsMake(0,0,0,0)];
    }
}

-(void)tableView:(UITableView *)tableView willDisplayCell:(UITableViewCell *)cell forRowAtIndexPath:(NSIndexPath *)indexPath
{
    if ([cell respondsToSelector:@selector(setSeparatorInset:)]) {
        [cell setSeparatorInset:UIEdgeInsetsZero];
    }
    
    if ([cell respondsToSelector:@selector(setLayoutMargins:)]) {
        [cell setLayoutMargins:UIEdgeInsetsZero];
    }
}
@end
